package com.qhit.util;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author 村头老杨头
 * @version 1.0
 * @date 2021/9/28 15:40
 */
public class BeanHandler {
    /**
     * @param clz  实体类的反射对象
     * @param rs   ResultSet 结果集对象
     * @return  实体类的对象
     */
    public static List handler(Class<?> clz, ResultSet rs) throws Exception{
        List list = new ArrayList();
        while (rs.next()){
            Object obj = clz.newInstance();
            ResultSetMetaData rsmd = rs.getMetaData();
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                String columnName = rsmd.getColumnName(i);
                Object columnValue = rs.getObject(columnName);

                Field field = clz.getDeclaredField(columnName);
                field.setAccessible(true);
                field.set(obj,columnValue);
            }
            list.add(obj);
        }
        return list;
    }
}
